package com.gjy.leetcode;

import org.junit.jupiter.api.Test;

import java.util.Arrays;

import static org.junit.jupiter.api.Assertions.assertEquals;

/**
 * 977. 有序数组的平方
 * 给你一个按 非递减顺序 排序的整数数组 nums，返回 每个数字的平方 组成的新数组，要求也按 非递减顺序 排序。
 *
 * @author 宫静雨
 * @version 1.0
 * @since 2023-01-04 09:52:35
 */
public class A977 {

    @Test
    public void test1() {
        int[] nums = {-4, -1, 0, 3, 10};
        int[] expected = {0, 1, 9, 16, 100};
        assertEquals(Arrays.toString(expected), Arrays.toString(sortedSquares2(nums)));
    }

    @Test
    public void test2() {
        int[] nums = {-7, -3, 2, 3, 11};
        int[] expected = {4, 9, 9, 49, 121};
        assertEquals(Arrays.toString(expected), Arrays.toString(sortedSquares2(nums)));
    }

    public int[] sortedSquares2(int[] nums) {
        int n = nums.length;
        int[] ans = new int[n];
        for (int i = 0, j = n - 1, pos = n - 1; i <= j; ) {
            int iv = nums[i] * nums[i];
            int jv = nums[j] * nums[j];
            if (iv > jv) {
                ans[pos] = iv;
                ++i;
            } else {
                ans[pos] = jv;
                --j;
            }
            --pos;
        }
        return ans;
    }

    public int[] sortedSquares(int[] nums) {
        for (int i = 0; i < nums.length; i++) {
            nums[i] = nums[i] * nums[i];
        }
        Arrays.sort(nums);
        return nums;
    }
}
